package cn.kimming.system.handler;


import cn.kimming.common.exception.SystemException;
import cn.kimming.common.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(SystemException.class)
    public Result handleSystemException(SystemException e) {
        e.printStackTrace();
        return new Result(false, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        List<ObjectError> errors = result.getAllErrors();
        StringBuilder sb = new StringBuilder(40);
        for (ObjectError error : errors) {
            sb.append(error.getDefaultMessage());
            sb.append(";");
        }
        e.printStackTrace();
        return new Result(false, sb.toString());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public Result handleException(Exception e) {
        e.printStackTrace();
        return new Result(false, "系统繁忙, 请稍后再试");
    }
}
